package io.sdph.products.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import io.sdph.core.database.Transaction;
import io.sdph.core.database.exceptions.DatabaseException;
import io.sdph.products.model.Product;
import io.sdph.userprofile.model.User;

@Repository
public class MagazineManagerDB implements MagazineManagerDAO {

	private static final Logger log = Logger.getLogger(MagazineManagerDB.class);
	
	@Override
	public Long getQuantity(final Product product) {
		Long quantity= null;
		
			try {
				Transaction tr_getQ = new Transaction() {
					
					@Override
					public Object doIt() throws DatabaseException, SQLException {
						
						
						
						ResultSet rs = select("select * from Magazine where idProduct= ?", product.getId() );
						Long quanity= null;
						if (rs.next()) {
							quanity =rs.getLong("quantity");

							
							// etc
						}

						return quanity;
					}
				};
				quantity = (Long) tr_getQ.getResult();
			} catch (DatabaseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		return quantity;
	}

	@Override
	public void setQuantity(final Product product, final Long quantity) {
		
		try {
			Transaction tr_setQ = new Transaction() {
				
				@Override
				public Object doIt() throws DatabaseException, SQLException {
					
					update("UPDATE Magazine set quantity=?  where idProduct=?;",quantity,product.getId());
					
					return null;
				}
			};
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void addQuantity(final Product product, final Long quantity) {
		
		
		try {
			Transaction tr_addQ = new Transaction() {
				
				@Override
				public Object doIt() throws DatabaseException, SQLException {
					
					insert("INSERT INTO Magazine VALUES ('?','?');", product.getId(),quantity);
					
					return null;
				}
			};
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
public void removeQuantity(final Product product) {
		
		
		try {
			Transaction tr_addQ = new Transaction() {
				
				@Override
				public Object doIt() throws DatabaseException, SQLException {
					
					insert("DELETE FROM Magazine WHERE idProduct=? ;", product.getId());
					
					return null;
				}
			};
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
